<?php

namespace Service\MoveUpDownService;

use Service\BaseService;
use Hyperf\DbConnection\Db;
use Service\Code\Normal;

class UpdateBatchService extends BaseService
{
    /**
     * 根据$index批量更新
     * @param $table
     * @param array $multipleData
     * @return array
     */
    public function updateBatch($table, array $multipleData = [],$index = 'id') : array
    {

        try {
            $tableName = $table->table;

            if (empty($multipleData)) {
                return Normal::returnCode(Normal::FAIL,'数据不能为空');
            }
            $firstRow  = current($multipleData);

            $updateColumn = array_keys($firstRow);

            $referenceColumn = $index;
            unset($updateColumn[0]);
            // 拼接sql语句
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets      = [];
            $bindings  = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn   = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings  = array_merge($bindings, $whereIn);
            $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            DB::connection('bbc_commodity')->update($updateSql, $bindings);
        } catch (\Exception $e) {
            return Normal::returnCode(Normal::FAIL,'批量更新数据失败：' . $e->getMessage());
        }
        return Normal::returnCode(Normal::SUC,'批量更新成功');
    }
}